axios.defaults.baseURL = ' https://hmajax.itheima.net'


function showToast(msg) {
    const myToast = document.querySelector('.my-toast')
    const toast = new bootstrap.Toast(myToast)
    document.querySelector('.toast-body').innerText = msg
    toast.show()
}
function checkLogin() {
    const toKen = localStorage.getItem('token')
    if (toKen === null) {
        showToast('请先登录')
        setTimeout(() => {
            location.href = 'login.html'
        }, 1500)
    }
}
function renderUername() {
    const username = localStorage.getItem('username')
    document.querySelector('.username').innerText = username
}
function logout() {
    document.querySelector('#logout').addEventListener('click', function () {
        localStorage.removeItem('token')
        localStorage.removeItem('username')
        showToast('退出成功')
        setTimeout(() => {
            location.href = './login.html'
        }, 1500)
    })
}
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    const token = localStorage.getItem('token')
    if (token) {
        config.headers.Authorization = token
    }
    return config
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response.data;
}, function (error) {
    // 对响应错误做点什么
    if (error.response.status === 401) {
        showToast('登录失败,请重新登录')
        localStorage.removeItem('username')
        localStorage.removeItem('token')
        setTimeout(() => {
            location.href = 'login.html'
        }, 1500)
    }
    return Promise.reject(error);
})